package chaos.main;

import java.util.ArrayList;
import java.util.HashSet;

import com.jme.app.SimpleGame;
import com.jme.input.InputHandler;
import com.jme.renderer.Camera;
import com.jme.scene.Node;
import com.jme.scene.state.LightState;
import com.jme.system.DisplaySystem;
import com.jme.util.Timer;

public abstract class CBFSystem extends SimpleGame {
	private static int MAX_GCORE_NUM = 30;
	final static ArrayList<GCore> activeCores = new ArrayList<GCore>(MAX_GCORE_NUM);
	final static ArrayList<GCore> holdedCores = new ArrayList<GCore>(MAX_GCORE_NUM);
	final static HashSet<GCore> initCoresList = new HashSet<GCore>(MAX_GCORE_NUM);
	
	protected void simpleUpdate() {
		//super.simpleUpdate();
		GCore cores[] = new GCore[activeCores.size()]; 
		activeCores.toArray(cores);
		for (int i = 0; i < cores.length; i++) {
			cores[i].updateCore(-1);
		}
	}
	
	public Node getRootNode() {
		return super.rootNode;
	}
	
	public Timer getTimer() {
		return super.timer;
	}
	
	public InputHandler getInput() {
		return super.input;
	}
	
	public DisplaySystem getDisplay() {
		return super.display;
	}
	
	public LightState getLightState() {
		return super.lightState;
	}
	
	public Camera getCam() {
		return cam;
	}
	
	public GCore getGCore(String name) {
		GCore cores[] = new GCore[activeCores.size()]; 
		activeCores.toArray(cores);
		for (int i = 0; i < cores.length; i++) {
			if(cores[i].getName().equals(name)) {
				return cores[i];
			}
		}
		
		cores = new GCore[holdedCores.size()];
		holdedCores.toArray(cores);
		for (int i = 0; i < cores.length; i++) {
			if(cores[i].getName().equals(name)) {
				return cores[i];
			}
		}
		return null;
	}
	
	public void addGCore(GCore gCore) {
		holdedCores.add(gCore);
	}
	
	public void removeGCore(GCore core) {
		activeCores.remove(core);
		holdedCores.add(core);
	}
	
	public void activeGCore(String name) {
		activeGCore( getGCore(name) );
	}
	
	public void activeGCore(GCore core) {
		holdedCores.remove(core);
		if( !initCoresList.contains(core) ) {
			core.init(this);
			initCoresList.add(core);
		}
		core.beforeActivate();
		activeCores.add(core);
	}
	
	public void deactiveGCore(String name) {
		deactiveGCore( getGCore(name) );
	}
	
	public void deactiveGCore(GCore core) {
		activeCores.remove(core);
		core.beforeDeactive();
		holdedCores.add(core);
	}
	
	public void removeGCore(String name) {
		GCore cores[] = new GCore[activeCores.size()]; 
		activeCores.toArray(cores);
		for (int i = 0; i < cores.length; i++) {
			if(cores[i].getName().equals(name)) {
				removeGCore(cores[i]);
				break;
			}
		}
	}
}